<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <!-- 搜索表单 -->
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="编号" prop="id">
            <el-input
              v-model="queryParams.id"
              placeholder="请输入产品编号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入产品名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="类别" prop="categoryId">
            <el-select v-model="queryParams.categoryId" placeholder="请选择">
              <el-option
                v-for="item in categoryOptions"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
                @keyup.enter.native="handleQuery"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <!-- 数据操作按钮 -->
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button
              v-hasAuthority="['pos:product:add']"
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>

          <el-col :span="1.5">
            <el-button
              v-hasAuthority="['pos:product:delete']"
              type="danger"
              icon="el-icon-delete"
              size="small"
              :disabled="single"
              @click="handleDelete"
              >删除</el-button
            >
          </el-col>
        </el-row>

        <!-- 数据展示Table -->
        <el-table
          v-loading="loading"
          :data="dataList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="ID" align="center" prop="id" width="55" />
          <el-table-column label="类别" align="center" prop="categoryName" />
          <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="尺寸" align="center" prop="size" />
          <el-table-column label="颜色" align="center" prop="color" />
          <el-table-column label="图片" align="center" prop="imgUrl">
            <template slot-scope="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.imgUrl"
                fit="fill"
                :lazy="true"
                :preview-src-list="[scope.row.imgUrl]"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column label="价格" align="center" prop="price" />
          <el-table-column
            label="价格折扣"
            align="center"
            prop="priceDiscount"
          />
          <el-table-column label="成本" align="center" prop="cost" />
          <el-table-column label="商品描述" align="center" prop="description" />

          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasAuthority="['pos:product:delete']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页加载 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.current"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-col>
    </el-row>

    <!-- 新增/修改对话框 默认不显示 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form :model="form" :rules="rules" ref="form" label-width="90px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="类别" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="价格折扣" prop="priceDiscount">
          <el-input v-model="form.priceDiscount" placeholder="请输入价格折扣" />
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-input v-model="form.color" placeholder="请输入颜色" />
        </el-form-item>
        <el-form-item label="成本" prop="cost">
          <el-input v-model="form.cost" placeholder="请输入成本" />
        </el-form-item>
        <el-form-item label="尺寸" prop="size">
          <el-select v-model="form.size" placeholder="请输入尺寸">
            <el-option
              v-for="item in sizeOptions"
              :key="item.id"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="图片" prop="imgUrl">
          <SingleUpload @modifyAvatar="changeUrl" :value="form.imgUrl" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  delProduct,
  addProduct,
  getProduct,
  updateProduct,
} from "@/api/product";
import { listCategorytByPage } from "@/api/category";
import SingleUpload from "@/components/upload/singleUpload";

export default {
  name: "ProductView",
  components: {
    SingleUpload,
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 表格数据
      dataList: [],
      // 查询参数
      // 查询参数
      queryParams: {
        categoryId: "",
        current: 1,
        id: "",
        name: "",
        pageSize: 10,
        price: "",
        sortField: "create_time",
        sortOrder: "ascend",
      },
      // 下拉框类别选项数据
      categoryOptions: [],
      // 尺寸数据
      sizeOptions: [
        { id: 1, value: "XS" },
        { id: 2, value: "S" },
        { id: 3, value: "M" },
        { id: 4, value: "L" },
        { id: 5, value: "XL" },
        { id: 6, value: "XXL" },
      ],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单
      form: {},
      // 表单校验
      rules: {
        productSn: [
          { required: true, message: "编号不能为空", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
      },
      // 总条数
      total: 0,
    };
  },
  created() {
    this.getList();
    this.getCategoryOptions();
  },
  methods: {
    changeUrl(imgUrl) {
      this.form.imgUrl = imgUrl;
    },
    getList() {
      this.loading = true;
      getProduct(this.queryParams).then((response) => {
        this.dataList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 查询下拉列表选型 */
    getCategoryOptions() {
      let queryParams = {
        current: 1,
        id: "",
        sortField: "create_time",
        sortOrder: "ascend",
        categoryName: "",
      };
      listCategorytByPage(queryParams).then((response) => {
        this.categoryOptions = response.data.records;
      });
      queryParams = null;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.getList();
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const productId = row.id || this.ids;
      this.$confirm('是否确认删除ID为"' + productId + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delProduct({ id: productId });
        })
        .then(() => {
          this.getList(); // 刷新数据
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.productId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 表单重置 */
    resetForm() {
      // 可进行数据初始化工作
      this.form = {
        size: "",
        name: "",
        price: "",
        categoryId: "",
        color: "",
      };
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加数据";
      this.resetForm();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm();
      // const productId = row.productId || this.ids;
      this.form = row;
      this.open = true;
      this.title = "修改数据";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.categoryId != "") {
            delete this.form.productSn;
            delete this.form.categoryName;
            delete this.form.createTime;
            delete this.form.updateTime;
            updateProduct(this.form).then((response) => {
              if (response.code == 200) {
                this.$message.success("修改成功");
                this.getList();
                this.cancel();
              }
            });
          } else {
            addProduct(this.form).then((response) => {
              if (response.code == 200) {
                this.$message.success("新增成功");
                this.getList();
                this.cancel();
              }
            });
          }
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.title = "";
      this.resetForm();
    },
    /** 处理分页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },
  },
};
</script>

<style scoped>
</style>